package com.shengwei.truck.driver.view.ui.mine.msgCenter;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.JsonMsgListData;
import com.shengwei.truck.driver.bean.MessageItem;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.databinding.FragmentNostartedTaskBinding;
import com.shengwei.truck.driver.utils.DateTimeUtils;
import com.shengwei.truck.driver.view.adapter.mine.MessageAdapter;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.vm.MsgListViewModel;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息列表：目前分为“系统消息列表”与“转派（共享）任务列表”，各TAB页重用这一个Fragment类
 */
public class MsgListFragment extends BaseFragment<MsgListViewModel, FragmentNostartedTaskBinding> {
    private static final String ARG_TAB_INDEX = "tab_index";
    int currentOperate = PULL_REFRESH; //0表示下拉刷新,1表示加载更多
    private static final int PULL_REFRESH = 0; //下拉刷新
    private static final int LOAD_MORE = 1;  //加载更多
    private MessageAdapter mAdapter;
    private int mPageNum;
    private int mPageSize = 20;
    private int mcurTabIndex;
    private List<MessageItem> mMsgList = new ArrayList<>();
    MsgListViewModel mShareViewModel;  //用于Activity中清除所有已读 事件通知到 fragment里，刷新列表已读显示。

    public static MsgListFragment newInstance(int tabIndex) {
        MsgListFragment fragment = new MsgListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(String.valueOf(ARG_TAB_INDEX), tabIndex);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            mcurTabIndex = getArguments().getInt(ARG_TAB_INDEX);
            Log.i(TAG,"mcurTabIndex="+mcurTabIndex);
        }
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView =  super.onCreateView(inflater,container,savedInstanceState);
        //初始化控件
        initView();
        //让fragment与它所附属的Activity公用一个viewModel:MsgListViewModel,这样fragment就可以和Activity利用livedata进行互相通信了
        mShareViewModel = ViewModelProviders.of(getActivity()).get(MsgListViewModel.class);
       // mViewModel = ViewModelProviders.of(getActivity()).get(MsgListViewModel.class);
        initLiveDataObersve();
        refreshLoadData();
        return rootView;
    }

    private void initLiveDataObersve() {
        //获取消息列表接口
        mViewModel.getMsgListLiveData().observe(getViewLifecycleOwner(), new Observer<Result<JsonMsgListData>>() {
            @Override
            public void onChanged(Result<JsonMsgListData> jsonTaskListDataResult) {

                Log.i(TAG,"getMsgListLiveData in MsgListFragment mcurTabIndex="+mcurTabIndex);
                jsonTaskListDataResult.handler(new OnCallback<JsonMsgListData>() {
                    @Override
                    public void onSuccess(JsonMsgListData data) {
                        if(currentOperate == PULL_REFRESH) {
                            dealMsgListForRefresh(data);
                        }
                        else {  //上拉加载更多
                             dealMsgListForLoadMore(data);
                        }
                        mDataBinding.refreshLayout.setRefreshing(false);
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                });
            }
        });

        //监听MsgCenterActivity的清除已读按钮
        mShareViewModel.getHasReadAllLiveData().observe(getViewLifecycleOwner(), new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String>searchUserDataResult) {
                Log.i(TAG,"getHasReadAllLiveData in MsgListFragment mcurTabIndex="+mcurTabIndex);
                for(MessageItem item : mMsgList) {
                   item.isRead = 1;
                }
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 处理  "下拉刷新" 时 从服务器获取到的 “消息列表”，显示到 UI列表上
     * @param msgListData： “消息列表”数据
     */
    public void dealMsgListForRefresh(JsonMsgListData msgListData) {
        //是否有下一页
        int totalpages = msgListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
        List<MessageItem> msgItemList =  msgListData.getContent();
        boolean isCurEmptyData = true;
        mMsgList.clear();

        if(msgItemList != null && msgItemList.size() > 0) {
            mDataBinding.taskRecyclerView.setVisibility(View.VISIBLE);
            mDataBinding.noDataLayout.setVisibility(View.GONE);
            isCurEmptyData = false;
            mMsgList.addAll(msgItemList);
        }
        else{
            mDataBinding.taskRecyclerView.setVisibility(View.GONE);
            mDataBinding.noDataLayout.setVisibility(View.VISIBLE);
        }
        mAdapter.notifyDataSetChanged(mMsgList);
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    /**
     * 处理  "上滑加载更多" 时 从服务器获取到的 “消息列表”，显示到 UI列表上
     * @param msgListData： “消息列表”数据
     */
    public void dealMsgListForLoadMore(JsonMsgListData msgListData) {
        //是否有下一页
        int totalpages = msgListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
        boolean isCurEmptyData = true;
        List<MessageItem> taskItemList =  msgListData.getContent();

        if(taskItemList != null && taskItemList.size() > 0) {
            int existSize = mMsgList.size();  //已有的条目个数
            isCurEmptyData = false;
            mMsgList.addAll(taskItemList);
            mAdapter.notifyItemRangeInserted(existSize - 1,taskItemList.size());
        }

        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_nostarted_task;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 初始化控件
     */
    public void initView()
    {
        //配置下拉刷新控件的圆形转圈的颜色
        mDataBinding.refreshLayout.setOnRefreshListener(mRefreshListener);
        int colorCircle1 = mContext.getResources().getColor(R.color.colorPrimary);
        int colorCircle2 = mContext.getResources().getColor(R.color.colorPrimaryDark);
        int colorCircle3 = mContext.getResources().getColor(R.color.colorPrimary);
        mDataBinding.refreshLayout.setColorSchemeColors(colorCircle1,colorCircle2,colorCircle3);

        //配置任务列表控件Recyclerview
        mDataBinding.taskRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mDataBinding.taskRecyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(mContext, R.color.line_color)));
        mDataBinding.taskRecyclerView.setSwipeItemClickListener(mItemClickListener); // RecyclerView Item点击监听。
        mDataBinding.taskRecyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
        mDataBinding.taskRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。
        mAdapter = new MessageAdapter(getActivity(),mMsgList);
        mDataBinding.taskRecyclerView.setAdapter(mAdapter);

        //请求服务器加载数据到任务列表。
        refreshLoadData();
    }



    /**
     * 第一次加载数据或下拉刷新
     */
    private void refreshLoadData() {
        mPageNum = 0;
        currentOperate = PULL_REFRESH;
        loadData();
    }
    private void loadMore(){
        currentOperate = LOAD_MORE;
        loadData();
    }

    public void loadData(){
        if(mcurTabIndex == 0) { //系统消息
            mViewModel.getMsgList(mPageNum,mPageSize,"3,4");
        }
        else{  //转派与共享
            mViewModel.getMsgList(mPageNum,mPageSize,"1,2");
        }
    }

    /**
     * 上拉时加载更多
     */
    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            loadMore();
        }
    };

    /**
     * 下拉刷新
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshLoadData();
        }
    };

    /**
     * Item点击监听
     */
    private SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            MessageItem messageItem = mMsgList.get(position);

            //消息未读，点击则变为已读
            if(messageItem.isRead == 0) {
                messageItem.isRead = 1; //点击就变为已读
                mAdapter.notifyDataSetChanged();
                String msgId = String.valueOf(messageItem.id);
                mViewModel.postHasRead(msgId,0); //0代表单条消息已读
            }
            goMsgDetail(messageItem);
        }
    };

    /**
     * 跳转到消息详情
     */
    public void goMsgDetail(MessageItem msgItem) {
        String title = msgItem.title;
        String time = DateTimeUtils.timeStampToDateString(msgItem.createTime);
        Intent i = new Intent(getActivity(),MsgDetailActivity.class);
        i.putExtra("fromPage","msgList");
        i.putExtra("title",title);  //消息类型
        i.putExtra("time",time); //时间
        i.putExtra("params",msgItem.params); //附加参数
        i.putExtra("content",msgItem.content); //内容
        startActivity(i);
    }

}
